/**
 *
 */
package com.yunhoo.cqq.document;

import com.yunhoo.cqq.announcement.AnnounceBean;
import com.yunhoo.cqq.impl.IbatisDocument;
import com.yunhoo.cqq.model.Document;
import com.yunhoo.cqq.model.TempFile;
import com.yunhoo.sys.util.common.FacesUtils;
import com.yunhoo.sys.util.common.LoginParam;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;

import java.util.Date;
import java.util.UUID;
import javax.el.ELContext;
import javax.faces.application.Application;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;
import org.richfaces.event.FileUploadEvent;
import org.richfaces.model.UploadedFile;


public class FileUploadAnnounceBean {

    private ArrayList<TempFile> files = new ArrayList<TempFile>();
    private int uploadsAvailable = 5;
    private boolean autoUpload = false;
    private boolean useFlash = false;
    private Document document;
    private String errmessage;
    private String fckurl;
    private int id=0;
    private String myurl="";

    public int getSize() {
        if (getFiles().size() > 0) {
            return getFiles().size();
        } else {
            return 0;
        }
    }

    public void paint(OutputStream stream, Object object) throws IOException {
        stream.write(getFiles().get((Integer) object).getData());
    }

   

     public void listener2(FileUploadEvent event) throws Exception {
        //将文件路径信息等以及文件允许访问的人员信息进行持久化操作
        FacesContext context = FacesContext.getCurrentInstance();
        ELContext elContext = context.getELContext();
        Application application = context.getApplication();
        AnnounceBean announce = (AnnounceBean) application.evaluateExpressionGet(context, "#{announce}", AnnounceBean.class);
        this.setErrmessage("");
        //做表单验证
        try {
            UploadedFile item = event.getUploadedFile();
            String uploadDirectory = FacesContext.getCurrentInstance().getExternalContext().getInitParameter ("uploadResources");//获取上传文件存储路径-web.xml
            String fileName = item.getName().substring(item.getName().lastIndexOf("\\") + 1);//文件名
            String saveFileName = getRandomString(fileName);
            String filepath = uploadDirectory + "\\" + saveFileName.substring(0, saveFileName.lastIndexOf(".")) + "\\";
            HttpServletRequest request = FacesUtils.getServletRequest();

//            String fckurl = "http://" + request.getRemoteHost() + ":" + request.getServerPort() + request.getContextPath() + "/uploadResources/" + saveFileName;
            String url = uploadDirectory + "\\" + saveFileName.substring(0, saveFileName.lastIndexOf(".")) + "\\" + fileName;
            //创建File对象,将上传的文件保存到指定文件夹下        
            File file1 = new File(filepath);
            if (file1.exists()) {
            } else {
                file1.mkdirs();
            }
            File file = new File(filepath, fileName + "");
            //将该数据流写入到指定文件中

            FileOutputStream out = new FileOutputStream(file);
            out.write(item.getData());
            //用于页面回显相关信息
            TempFile tempFile = new TempFile();
            tempFile.setLength(item.getData().length);
            tempFile.setName(fileName);
            tempFile.setData(item.getData());
            files.add(tempFile);
            uploadsAvailable--;
            //得到所有能够访问该文件的人员
            //根据名字遍历结束，得到所有具备查看该文档权限的人员集合userList
            //将文档信息插入数据库，首先包装文档信息
            Document documentTemp = new Document();
            documentTemp.setTitle(fileName);
            documentTemp.setDescription(fileName);
            documentTemp.setDocSize(CountFileSize(tempFile.getLength()));
            documentTemp.setUploadDate(new Date());
            documentTemp.setUserName(LoginParam.getPer().getCpsn_number());//上传的人员
//            documentTemp.setType(announce.getType());
//            System.out.println("type:"+announce.getType().getId());
            documentTemp.setUrl(url);
//            System.out.println(fileName + "|" + CountFileSize(tempFile.getLength()) + "|" + login.getUsername() + "|" + url + "|" + documentTemp.getType());
//            IbatisDocument.insertDocument(documentTemp);
            id=IbatisDocument.getTopDocId();
            myurl=url;
            
//            System.out.println(id);
            
            //将文档信息插入数据库
            //IbatisDocument.insertDocument(documentTemp);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static String CountFileSize(long size) {
        if (size < 1024l) {
            return size + "B";
        } else if (size < (1024l * 1024l)) {
            return Math.round((size * 100 >> 10)) / 100.00 + "KB";
        } else if (size < (1024l * 1024l * 1024l)) {
            return (Math.round((size * 100 >> 20)) / 100.00) + "MB";
        } else {
            return Math.round((size * 100 >> 30)) / 100.00 + "GB";
        }
    }

    public String getRandomString(String fileName) {
        if (fileName.lastIndexOf(".") != -1) {
            return UUID.randomUUID().toString() + fileName.substring(fileName.lastIndexOf("."));
        } else {
            return UUID.randomUUID().toString() + fileName;
        }
    }

    public void uploadFiles() {
    }

    public String getErrmessage() {
        return errmessage;
    }

    public void setErrmessage(String errmessage) {
        this.errmessage = errmessage;
    }

    public String clearUploadData() {
        files.clear();
        setUploadsAvailable(5);
        return null;
    }

    public long getTimeStamp() {
        return System.currentTimeMillis();
    }

    public ArrayList<TempFile> getFiles() {
        return files;
    }

    public void setFiles(ArrayList<TempFile> files) {
        this.files = files;
    }

    public int getUploadsAvailable() {
        return uploadsAvailable;
    }

    public void setUploadsAvailable(int uploadsAvailable) {
        this.uploadsAvailable = uploadsAvailable;
    }

    public boolean isAutoUpload() {
        return autoUpload;
    }

    public void setAutoUpload(boolean autoUpload) {
        this.autoUpload = autoUpload;
    }

    public boolean isUseFlash() {
        return useFlash;
    }

    public void setUseFlash(boolean useFlash) {
        this.useFlash = useFlash;
    }

    public Document getDocument() {
        return document;
    }

    public void setDocument(Document document) {
        this.document = document;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getMyurl() {
        return myurl;
    }

    public void setMyurl(String myurl) {
        this.myurl = myurl;
    }

    public String getFckurl() {
        HttpServletRequest request = FacesUtils.getServletRequest();
        String str = request.getRemoteHost();
        if (str.equals("127.0.0.1")) {
            str = "localhost";
        }
        fckurl = "http://" + str + ":" + request.getServerPort() + request.getContextPath();

//        System.out.println(fckurl);
        return fckurl;
    }

    public void setFckurl(String fckurl) {
        this.fckurl = fckurl;
    }
}
